package com.sn.springboot_netty.common.advice;

import com.sn.springboot_netty.common.exception.MyException;
import com.sn.springboot_netty.common.result.Result;
import com.sn.springboot_netty.common.result.ResultEnum;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author fyy
 * @Description
 * @Date 2020/6/16 10:40
 */
@RestControllerAdvice
public class MyExceptionAdvice {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultException(HttpServletRequest request,Exception e){
        e.printStackTrace();
        return Result.builder()
                .code(ResultEnum.EXCEPTION.getCode())
                .message(ResultEnum.EXCEPTION.getMsg())
                .build();
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Result myException(HttpServletRequest request,MyException e){
        e.printStackTrace();
        Integer code = e.getCode();
        String message = e.getMessage();

        if(null == e.getCode()){
            code = ResultEnum.EXCEPTION.getCode();
        }

        if (null == e.getMessage()){
            message = ResultEnum.EXCEPTION.getMsg();
        }

        return Result.builder()
                .code(code)
                .message(message)
                .build();
    }

}
